package lc.com.lcpicturebackend.manager.websocket.disruptor;

import cn.hutool.json.JSONUtil;
import com.lmax.disruptor.WorkHandler;
import lc.com.lcpicturebackend.manager.websocket.PictureEditHandler;
import lc.com.lcpicturebackend.manager.websocket.model.PictureEditMessageTypeEnum;
import lc.com.lcpicturebackend.manager.websocket.model.PictureEditRequestMessage;
import lc.com.lcpicturebackend.manager.websocket.model.PictureEditResponseMessage;
import lc.com.lcpicturebackend.model.entity.User;
import lc.com.lcpicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import jakarta.annotation.Resource;
import java.util.Map;

import static lc.com.lcpicturebackend.manager.websocket.model.PictureEditMessageTypeEnum.EDIT_ACTION;
import static lc.com.lcpicturebackend.manager.websocket.model.PictureEditMessageTypeEnum.ENTER_EDIT;

/**
 * 功能： 图片编辑事件处理器（消费者）
 * 将不同的message类型分发到不同处理器中
 * 作者：lc
 * 日期：2025/4/28 15:16
 */
@Component
@Slf4j
public class PictureEditEventWorkHandler implements WorkHandler<PictureEditEvent> {

    @Resource
    @Lazy
    private PictureEditHandler pictureEditHandler;

    @Resource
    private UserService userService;
    @Override
    public void onEvent(PictureEditEvent pictureEditEvent) throws Exception {
        PictureEditRequestMessage pictureEditRequestMessage = pictureEditEvent.getPictureEditRequestMessage();
        WebSocketSession session = pictureEditEvent.getWebSocketSession();
        Long pictureId = pictureEditEvent.getPictureId();
        User user = pictureEditEvent.getUser();
        String type = pictureEditRequestMessage.getType();
        PictureEditMessageTypeEnum pictureEditMessageTypeEnum = PictureEditMessageTypeEnum.getEnumByValue(type);
        switch (pictureEditMessageTypeEnum) {
            case ENTER_EDIT:
                pictureEditHandler.handleEnterEdit(pictureEditRequestMessage, session, user, pictureId);
                break;
            case EDIT_ACTION:
                pictureEditHandler.handleEnterAction(pictureEditRequestMessage, session, user, pictureId);
                break;
            case EXIT_EDIT:
                pictureEditHandler.handleExitEdit(pictureEditRequestMessage, session, user, pictureId);
                break;
            default:
                PictureEditResponseMessage pictureEditResponseMessage = new PictureEditResponseMessage();
                pictureEditResponseMessage.setType(PictureEditMessageTypeEnum.ERROR.getValue());
                pictureEditResponseMessage.setMessage("未知消息类型");
                pictureEditResponseMessage.setUser(userService.getUserVO(user));
                session.sendMessage(new TextMessage(JSONUtil.toJsonStr(pictureEditResponseMessage)));
                break;
        }
    }
}
